<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/07/18 12:37:09 $)
// $RCSfile: report_department.php,v $ : $Revision: 1.7 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

@define("DATENOW", time());

require_once ("./includes/Graph/functions_charts.php");

$template->assign("calendar", true);

if (empty($_REQUEST["datefrom"]) && empty($_REQUEST["dateto"]))
{
	$_prevday = DATENOW-86400;
	$_gdatefrom = generateCalendarTimeline(mktime(0,0,0,date("m", DATENOW), 1, date("Y", DATENOW)));
	$_gdateto = generateCalendarTimeline(DATENOW);
} else {
	$_gdatefrom = $_REQUEST["datefrom"];
	$_gdateto = $_REQUEST["dateto"];
}

$_datefrom = getCalendarDateline($_gdatefrom);
$_dateto = getCalendarDateline($_gdateto);
$_dateto = mktime(23,59,59,date("m", $_dateto), date("d", $_dateto), date("Y", $_dateto));

unset($_staffsql);
unset($_statussql);

if (!empty($_REQUEST["filterticketstatusid"]))
{
	$_statussql = " AND `ticketstatusid` = '". intval($_REQUEST["filterticketstatusid"]) ."'";
}

$_datestart = $_datefrom;

$_daylist = array();
while ($_datestart <= $_dateto)
{
	$_daylist[] = date("d-n-Y", $_datestart);
	$_datestart += 86400;
}

$_filterticketidlist = $_filterticketpostidlist = array();
if (!empty($_REQUEST["filterstaffid"]))
{
	$dbCore->query("SELECT `ticketpostid` FROM `". TABLE_PREFIX ."ticketposts` WHERE `creator` = '". POST_STAFF ."' AND `staffid` = '". intval($_REQUEST["filterstaffid"]) ."' AND DATE_FORMAT(FROM_UNIXTIME(dateline), '%d-%c-%Y') IN (". buildIN($_daylist) .");");
	while ($dbCore->nextRecord())
	{
		$_filterticketpostidlist[] = $dbCore->Record["ticketpostid"];
	}

	$_staffsql = " AND `ownerstaffid` = '". intval($_REQUEST["filterstaffid"]) ."'";
	$_staffsql = " AND `ticketid` IN (". buildIN($_filterticketidlist) .")";
}

$_stat = $_statstatus = $_statdep = array();
$_max = 0;

if (count($_filterticketpostidlist))
{
	$dbCore->query("SELECT COUNT(*) AS totalitems, DATE_FORMAT(FROM_UNIXTIME(ticketposts.dateline), '%d') AS outdate, tickets.departmentid, tickets.ticketstatusid FROM `". TABLE_PREFIX ."ticketposts` AS ticketposts LEFT JOIN `". TABLE_PREFIX ."tickets` AS tickets ON (ticketposts.ticketid = tickets.ticketid) WHERE ticketposts.ticketpostid IN (". buildIN($_filterticketpostidlist) .")". $_statussql ." GROUP BY DATE_FORMAT(FROM_UNIXTIME(ticketposts.dateline), '%d-%c-%Y'), tickets.departmentid, tickets.ticketstatusid;");
} else {
	if ($_GET["custom"] == 1)
	{
		$dbCore->query("SELECT COUNT(*) AS totalitems, DATE_FORMAT(FROM_UNIXTIME(dateline), '%d') AS outdate, departmentid, ticketstatusid FROM `". TABLE_PREFIX ."tickets` WHERE DATE_FORMAT(FROM_UNIXTIME(dateline), '%d-%c-%Y') IN (". buildIN($_daylist) .")". $_staffsql . $_statussql ." GROUP BY DATE_FORMAT(FROM_UNIXTIME(dateline), '%d-%c-%Y'), departmentid, ticketstatusid;");
	} else {
		$dbCore->query("SELECT COUNT(*) AS totalitems, DATE_FORMAT(FROM_UNIXTIME(lastactivity), '%d') AS outdate, departmentid, ticketstatusid FROM `". TABLE_PREFIX ."tickets` WHERE DATE_FORMAT(FROM_UNIXTIME(lastactivity), '%d-%c-%Y') IN (". buildIN($_daylist) .")". $_staffsql . $_statussql ." GROUP BY DATE_FORMAT(FROM_UNIXTIME(lastactivity), '%d-%c-%Y'), departmentid, ticketstatusid;");
	}
}
while ($dbCore->nextRecord())
{
	if ($dbCore->Record["totalitems"] > $_max && $dbCore->Record["departmentid"] == $_REQUEST["departmentid"])
	{
		$_max = $dbCore->Record["totalitems"];
	}

//	print_r($dbCore->Record);

	$_stat[$dbCore->Record["departmentid"]][$dbCore->Record["outdate"]] += $dbCore->Record["totalitems"];
	$_statstatus[$dbCore->Record["departmentid"]][$dbCore->Record["ticketstatusid"]] += $dbCore->Record["totalitems"];
	$_statdep[$dbCore->Record["departmentid"]] += $dbCore->Record["totalitems"];
}

if ($_REQUEST["do"] == "chart")
{
		$chart[ 'axis_category' ] = array ( 'size'=>10, 'color'=>"000000", 'alpha'=>50, 'font'=>"verdana", 'bold'=>true, 'skip'=>0 ,'orientation'=>"horizontal" ); 
		$chart[ 'axis_ticks' ] = array ( 'value_ticks'=>true, 'category_ticks'=>true, 'major_thickness'=>2, 'minor_thickness'=>1, 'minor_count'=>1, 'major_color'=>"000000", 'minor_color'=>"222222" ,'position'=>"outside" );
		$chart[ 'axis_value' ] = array (  'min'=> 0, 'max'=> round($_max), 'font'=>"verdana", 'bold'=>true, 'size'=>10, 'color'=>"000000", 'alpha'=>50, 'steps'=>6, 'prefix'=>"", 'suffix'=>"", 'decimals'=>0, 'separator'=>"", 'show_min'=>true );

		$chart[ 'chart_border' ] = array ( 'color'=>"000000", 'top_thickness'=>2, 'bottom_thickness'=>2, 'left_thickness'=>2, 'right_thickness'=>2 );

		$index = 1;
		$_chartindex = array("");
		$_chartvalue = array("Values");

		if (_is_array($_stat[$_REQUEST["departmentid"]]))
		{
			foreach ($_stat[$_REQUEST["departmentid"]] as $key=>$val)
			{
	//			echo $key . " - ".$val."<BR />";
				$_chartindex[] = $key;
				$_chartvalue[] = $val;
				$index++;
			}
		}
		$chart[ 'chart_data' ] = array ( $_chartindex, $_chartvalue);

		$chart[ 'chart_grid_h' ] = array ( 'alpha'=>10, 'color'=>"000000", 'thickness'=>1, 'type'=>"solid" );
		$chart[ 'chart_grid_v' ] = array ( 'alpha'=>0, 'color'=>"000000", 'thickness'=>1, 'type'=>"solid" );
		$chart[ 'chart_pref' ] = array ( 'line_thickness'=>2, 'point_shape'=>"circle", 'fill_shape'=>false );
		$chart[ 'chart_rect' ] = array ( 'x'=>70, 'y'=>25, 'width'=>635, 'height'=>200, 'positive_color'=>"000000", 'positive_alpha'=>30, 'negative_color'=>"ff0000",  'negative_alpha'=>10 );
		$chart[ 'chart_type' ] = "Line";
		$chart[ 'chart_value' ] = array ( 'prefix'=>"", 'suffix'=>"", 'decimals'=>0, 'separator'=>"", 'position'=>"cursor", 'hide_zero'=>true, 'as_percentage'=>false, 'font'=>"verdana", 'bold'=>true, 'size'=>12, 'color'=>"000000", 'alpha'=>75 );

		$chart[ 'legend_rect' ] = array ( 'x'=>-100, 'y'=>-100, 'width'=>10, 'height'=>10, 'margin'=>10 ); 

		$chart[ 'series_color' ] = array ( "ff4444" ); 

		SendChartData ( $chart );


	exit;
}

$interface->staffHeader($_SWIFT["language"]["tickets"]." &gt; ".$_SWIFT["language"]["reports"], 2);

renderTicketTree();
$interface->staffNavBar('<a href="index.php?_m=tickets&_a=manage" title="'.$_SWIFT["language"]["tickets"].'">'.$_SWIFT["language"]["tickets"].'</a> &raquo; '.'<a href="index.php?_m=tickets&_a=reports&type=worksummary" title="'.$_SWIFT["language"]["reports"].'">'.$_SWIFT["language"]["reports"].'</a> &raquo; '.'<a href="index.php?_m=tickets&_a=reports&type=department" title="'.$_SWIFT["language"]["departmentrep"].'">'.$_SWIFT["language"]["departmentrep"].'</a>', "", 2);

printInfoBox($infomessage);
printErrorBox($errormessage);

?>
<form name="swiftform" action="index.php" method="POST"><fieldset class="swiftfieldset">
<legend><?=$_SWIFT["language"]["filter"]?></legend>
<table width="100%"  border="0" cellspacing="1" cellpadding="2" class="tborder">
<tr>
<td width="100" class="row1" nowrap><?=$_SWIFT["language"]["fildate"]?></td>
<td class="row2"><input type="text" name="datefrom" id="datefrom" size="12" readonly="1" value="<?=iif(!empty($_gdatefrom), $_gdatefrom)?>" class="swifttext" onclick="return showCalendar('datefrom', '<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>');" />&nbsp;<img src="<?=$_SWIFT["themepath"]?>calendar.gif" id="datefromtrigger" style="cursor: pointer;" align="absmiddle" onclick="return showCalendar('datefrom', '<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>');" /> <?=$_SWIFT["language"]["filto"]?> <input type="text" name="dateto" id="dateto" size="12" readonly="1" value="<?=iif(!empty($_gdateto), $_gdateto)?>" class="swifttext" onclick="return showCalendar('dateto', '<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>');" />&nbsp;<img src="<?=$_SWIFT["themepath"]?>calendar.gif" id="datetotrigger" style="cursor: pointer;" align="absmiddle" onclick="return showCalendar('dateto', '<?=iif($_SWIFT["settings"]["dt_caltype"]=="us", "%m/%d/%Y", "%d/%m/%Y")?>');" /></td>

<td width="100" class="row1" nowrap><?=$_SWIFT["language"]["filstaff"]?></td>
<td class="row2">
<select name="filterstaffid" class="swiftselect">
<option value="0"<?=iif(empty($_POST["filterstaffid"]), " selected")?>><?=$_SWIFT["language"]["filnotselected"]?></option>
<?
foreach ($_SWIFT["staffcache"] as $key=>$val)
{
	?><option value="<?=$val["staffid"]?>"<?=iif($_POST["filterstaffid"]==$val["staffid"], " selected")?>><?=htmlspecialchars($val["fullname"])?></option><?
}
?></select>
</td>

<td width="100" class="row1" nowrap><?=$_SWIFT["language"]["filstatus"]?></td>
<td class="row2">
<select name="filterticketstatusid" class="swiftselect">
<option value="0"<?=iif(empty($_POST["filterticketstatusid"]), " selected")?>><?=$_SWIFT["language"]["filnotselected"]?></option>
<?
foreach ($_SWIFT["statuscache"] as $key=>$val)
{
	?><option value="<?=$val["ticketstatusid"]?>" style="color:<?=$val["statuscolor"]?>"<?=iif($_POST["filterticketstatusid"]==$val["ticketstatusid"], " selected")?>><?=htmlspecialchars($val["title"])?></option><?
}
?></select>
</td>



<td width="100" class="row2" align="right" nowrap><input type="submit" class="yellowbutton" name="filter" value="<?=$_SWIFT["language"]["filter"]?>"></td>
</tr>
</table>
</fieldset><BR />
<input type="hidden" name="_m" value="tickets"><input type="hidden" name="_a" value="reports"><input type="hidden" name="type" value="department">
</form>
<?

$_colspan = count($_SWIFT["statuscache"]);

foreach ($_SWIFT["departmentcache"] as $key=>$val)
{
	if ($val["departmentmodule"] != MODULE_TICKETS)
	{
		continue;
	}

	printMainTableHeader(htmlspecialchars($val["title"])." (". intval($_statdep[$val["departmentid"]]) .")");

	$data = array();
	$index = 0;
	foreach ($_SWIFT["statuscache"] as $statkey=>$statval)
	{
		$data[$index]["value"] = '<span class="smalltext"><font color="'. $statval["statuscolor"] .'">'. htmlspecialchars($statval["title"])."</font>: ".intval($_statstatus[$val["departmentid"]][$statval["ticketstatusid"]]) .'</span>'.SWIFT_CRLF;
		$data[$index]["align"] = "left";
		$index++;
	}
	printDataRow($data);

//	echo "index.php?_m=tickets&_a=reports&type=department&do=chart&datefrom=". $_gdatefrom ."&dateto=".$_gdateto."&filterstaffid=".intval($_POST["filterstaffid"])."&filterticketstatusid=".intval($_POST["filterticketstatusid"])."&departmentid=".intval($val["departmentid"]);

	$data = array();
	$data[0]["value"] = InsertChart($_SWIFT["swiftpath"]."includes/Graph/charts.swf", "index.php?_m=tickets&_a=reports&type=department&do=chart&datefrom=". $_gdatefrom ."&dateto=".$_gdateto."&filterstaffid=".intval($_POST["filterstaffid"])."&filterticketstatusid=".intval($_POST["filterticketstatusid"])."&departmentid=".intval($val["departmentid"])."&custom=".intval($_GET["custom"]), 750, 250, "666666", true);
	$data[0]["align"] = "left";
	$data[0]["colspan"] = $_colspan;
	printDataRow($data);

	printMainTableFooter();
	echo "<BR />";
}



$template->assign("backurl", "index.php?_m=tickets&_a=manage");

$interface->staffFooter();

?>